package com.exam.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exam.pojo.User;
import com.exam.service.UserService;
import com.exam.util.StringUtils;
import com.exam.vo.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author XiaoKai
 * @since 2021-07-30
 */
@RestController
@RequestMapping("/api")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public ResultData<Map<String, Object>> login(@RequestBody User user){
        Assert.notNull(user,"请输入用户名");
        String account= user.getAccount();
        Assert.isTrue(StringUtils.isNotEmpty(account),"请输入用户名");
        String password = user.getPassword();
        Assert.isTrue(StringUtils.isNotEmpty(password),"请输入密码");
        HashMap<String, Object> result = new HashMap<>();
        HttpSession session = getSession();
        User login = userService.login(account, password);
        //        设置session
        session.setAttribute(SESSION_KEY_LOGIN_USER, login);
        result.put("userInfo", login);
        return new ResultData<Map<String, Object>>(result);
    }
    @GetMapping("/myselfInfo")
    public ResultData<Map<String,Object>> getMyselfInfo(){
        Map map = new HashMap();
        User myselfInfo = (User) getSession().getAttribute(SESSION_KEY_LOGIN_USER);
        if (myselfInfo!=null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id",myselfInfo.getId());
            User user = userService.getBaseMapper().selectOne(queryWrapper);
            map.put("myselfInfo",user);
            return ResultData.success(map);
        }else{
            return ResultData.error(401,"未登录");
        }
    }
    @GetMapping("/loginOut")
    public ResultData<Map<String,Object>> loginOut(){
        getSession().removeAttribute(SESSION_KEY_LOGIN_USER);
        return ResultData.success(null);
    }
}

